package cn.waka.sys.admin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import cn.waka.sys.admin.object.Result;
import cn.waka.sys.admin.service.ScheduleService;
import cn.waka.sys.admin.utils.Validator;

@RestController
@RequestMapping("/schedule")
public class ScheduleController extends BaseController {

	private ScheduleService scheduleService;

	@Autowired
	public void setScheduleService(ScheduleService scheduleService) {
		this.scheduleService = scheduleService;
	}
	
	@RequestMapping(path = "/index",name="课程列表", produces = "text/html; charset=UTF-8")
	public ModelAndView getScheduleList(HttpServletRequest request, HttpServletResponse response){
		List<Map<String,Object>> slist=scheduleService.getScheduleList();
		ModelAndView mv=new ModelAndView();
		mv.addObject("slist", slist);
		return mv;
	}
	
	@RequestMapping(path = "/form",name="查一个课程", produces = "text/html; charset=UTF-8")
	public ModelAndView getSchedule(HttpServletRequest request, HttpServletResponse response){
		String idStr=request.getParameter("schedule_id");
		int id=0;
		Map<String,Object> schedule= new HashMap<String, Object>();
		if(idStr!=null&&Validator.isNum(idStr)){
			id=Integer.parseInt(idStr);
			schedule=scheduleService.getSchedule(id);
		}else {
			schedule.put("week_day", 0);
			schedule.put("title", null);
			schedule.put("resource_id", null);
			schedule.put("schedule_id", null);
		}
		ModelAndView mv=new ModelAndView();
		mv.addObject("schedule", schedule);
		return mv;
	}
	
	@RequestMapping(path = "/save",name="保存课程", produces = "application/json; charset=UTF-8")
	public Result add(HttpServletRequest request) {
		String idStr=request.getParameter("id");
		int id=0;
		if(idStr!=null&&Validator.isNum(idStr)){
			id=Integer.parseInt(idStr);
		}
		int week_day=Integer.parseInt(request.getParameter("week_day"));
		int resource_id=Integer.parseInt(request.getParameter("resource_id"));
		
		int rst = scheduleService.save(id,resource_id, week_day);
		Result rs=ok();
		if(rst>0){
			rs.setMsg("保存成功!");
			rs.setCode(1);
		}else{
			rs.setMsg("保存失败!");
			rs.setCode(0);
		}
		return rs;
	}
	
	@RequestMapping(path = "/delete",name="删除课程", produces = "application/json; charset=UTF-8")
	public Result delete(HttpServletRequest request) {
		int schedule_id=Integer.parseInt(request.getParameter("id"));
		int rst = scheduleService.delete(schedule_id);
		Result rs=ok();
		if(rst>0){
			rs.setMsg("操作成功!");
			rs.setCode(1);
		}else{
			rs.setMsg("操作失败!");
			rs.setCode(0);
		}
		return rs;
	}

}
